<?php

namespace backend\controllers;

use Yii;
use backend\models\Product;
use backend\models\ProductSearch;
//use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use crazyfd\qiniu\Qiniu;
use backend\models\Category;

/**
 * ProductController implements the CRUD actions for Product model.
 */
//class ProductController extends Controller
class ProductController extends SuperController {

	/**
	 * @inheritdoc
	 */
	public function behaviors() {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['POST'],
				],
			],
		];
	}

	/**
	 * Lists all Product models.
	 * @return mixed
	 */
	public function actionIndex() {
		$searchModel = new ProductSearch();
		$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

		return $this->render('index', [
					'searchModel' => $searchModel,
					'dataProvider' => $dataProvider,
		]);
	}

	/**
	 * Displays a single Product model.
	 * @param integer $id
	 * @return mixed
	 */
	public function actionView($id) {
		return $this->render('view', [
					'model' => $this->findModel($id),
		]);
	}

	/**
	 * Creates a new Product model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 * @return mixed
	 */
	public function actionCreate() {
		$model = new Product();
		$pictures = new \backend\models\Uploads();
		$cover = new \backend\models\Upload();
		if ($model->load(Yii::$app->request->post())) {
			$pictureFiles = UploadedFile::getInstances($pictures, 'file');
			$coverFile = UploadedFile::getInstances($cover, 'file');
			$files = $this->upload($coverFile, $pictureFiles);
			if ($coverFile == null || $pictureFiles == null) {
				return $this->error("没有选中上传文件");
			}
			//把分类加到description后面
			$categotyModel = Category::find()->where('categoryId=:categoryId', [':categoryId' => $model->categoryId])->one();
			while (isset($categotyModel)) {
				$model->description .= " " . $categotyModel->title;
				$categotyModel = Category::find()->where('categoryId=:categoryId', [':categoryId' => $categotyModel->parentId])->one();
			}
			$model->cover = $files['cover'];
			$model->pictures = $files['pictures'];
			if ($model->validate() && $model->save()) {
				return $this->redirect(['view', 'id' => $model->productId]);
//                return $this->success();
			}
		}
		return $this->render('create', [
					'model' => $model,
					'pictures' => $pictures,
					'cover' => $cover,
		]);
	}

	private function upload($coverFile, $pictureFiles) {

		$qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET);
		$pictures = [];
		$cover = null;
		if ($coverFile != null) {
			$key = uniqid();
			$qiniu->uploadFile($coverFile[0]->tempName, $key);
			$cover = $qiniu->getLink($key);
		}
		if ($pictureFiles != null) {
			foreach ($pictureFiles as $k => $file) {
				$key = uniqid();
				$qiniu->uploadFile($file->tempName, $key);
				$pictures[$key] = $qiniu->getLink($key);
			}
		}
		return ['cover' => $cover, 'pictures' => json_encode($pictures)];
	}

	/**
	 * Updates an existing Product model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id
	 * @return mixed
	 */
	public function actionUpdate($id) {
		$model = $this->findModel($id);
		$pictures = new \backend\models\Uploads();
		$cover = new \backend\models\Upload();
		if ($model->load(Yii::$app->request->post())) {
			$qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET);
			$pictureFiles = UploadedFile::getInstances($pictures, 'file');
			$coverFile = UploadedFile::getInstances($cover, 'file');
			if ($coverFile != null) {
				$coverKey = basename($model->cover);
				$qiniu->delete($coverKey);
			}
//            if ($pictureFiles != null) {
//                $pictures = json_decode($model->pictures, true);
//                foreach ($pictures as $key => $file) {
//                    $qiniu->delete($key);
//                }
//            }
			$files = $this->upload($coverFile, $pictureFiles);
			if ($files['cover'] != NULL) {
				$model->cover = $files['cover'];
			}
			if ($files['pictures'] != "[]") { //json_encode加密过,所以要字符串
				//json_encode加密过,所以要字符串
				//json_解密后是object所以要类型转换
				$oldPictures = json_decode($model->pictures, true);
				$newPictures = json_decode($files['pictures'], true);
//               echo "<pre>";
//               var_dump($oldPictures);
//               var_dump($newPictures);
//               echo "</pre>";
//               exit;
				$pictures = array_merge($oldPictures, $newPictures);
				$pictures = json_encode($pictures);
				$model->pictures = $pictures;
			}
			if ($model->save()) {
				return $this->redirect(['view', 'id' => $model->productId]);
			}
		}


		return $this->render('update', [
					'model' => $model,
					'pictures' => $pictures,
					'cover' => $cover,
		]);
	}

	/**
	 * Deletes an existing Product model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id
	 * @return mixed
	 */
	public function actionDelete($id) {
		$model = $this->findModel($id);
		$qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET);
		$coverKey = basename($model->cover);
		$qiniu->delete($coverKey);
		$pictures = json_decode($model->pictures, true);
		foreach ($pictures as $key => $file) {
			$qiniu->delete($key);
		}
		$model->delete();


		return $this->redirect(['index']);
	}

	/**
	 * Finds the Product model based on its primary key value.
	 * If the model is not found, a 404 HTTP exception will be thrown.
	 * @param integer $id
	 * @return Product the loaded model
	 * @throws NotFoundHttpException if the model cannot be found
	 */
	protected function findModel($id) {
		if (($model = Product::findOne($id)) !== null) {
			return $model;
		} else {
			throw new NotFoundHttpException('The requested page does not exist.');
		}
	}

	/**
	 * 将图片转换为HTML格式显示
	 * @param $id int
	 * @param $picturesAddress string 图片地址
	 * @param $type boolean 选择链接的方式还是ajax的方式
	 * @throws HttpException
	 * @return string
	 */
	public static function translatePictures($id, $picturesAddress, $type = 0) {
		$actionId = Yii::$app->controller->action->id;
//        echo "<pre>";
//        var_dump($str);
//        echo "</pre>";
//        exit;
		$result = "<div class = 'row'id = 'showpicture'>";
		if ($type == 0) {
			$i = 0;
			foreach ((array) json_decode($picturesAddress, true) as $key => $value) {
				$result .= "<div id = $key class='col-sm-2'><img  src= //$value style='width: 150px;
    height: 150px;'> <a class='btn btn-info' href='#showpicture' onclick=doDelete('$id','$key')>"
						. "删除</a></div>";
				$i++;
				if ($i % 5 == 0) {
					$result .= "</div><div class='row'>";
				}
			}
		} else {
			$i = 0;
			foreach ((array) json_decode($picturesAddress, true) as $key => $value) {
				$result .= "<div id = $key class='col-md-2'><img  src= //$value style='width: 200px;
    height: 200px;'> <a href = remove?id=$id&key=$key&actionId=$actionId class='btn btn-info'>"
						. "删除</a></div>";
				$i++;
				if ($i % 5 == 0) {
					$result .= "</div><div class='row'>";
				}
			}
		}
		//没有使用ajax
//        foreach ((array) json_decode($picturesAddress, true) as $key => $value) {
//            $result .= "<div id = $key class='col-md-1'><img  src= //$value style='width: 100px;
//    height: 100px;'> <a href = remove?id=$id&key=$key&actionId=$actionId>"
//                    . "<button class='btn btn-info'>删除</button></a></div>";
//        }

		$result .= "</div>";
		return $result;
	}

	/**
	 * @function 将云端的图片移除
	 * @param $key
	 * @throws HttpException
	 * @return null;
	 */
	public function actionRemove($id = 0, $key = 0, $actionId = 0) {

		if (!Yii::$app->request->isAjax) {
			$model = $this->findModel($id);
			$qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET);
			$pictures = json_decode($model->pictures, true);
			unset($pictures[$key]);
			$newPictures = json_encode($pictures);
			$model->pictures = $newPictures;
			$qiniu->delete($key);
			$model->save();
			return $this->success($actionId . "?id=" . $id, 0.5);
		} else {
			$data = Yii::$app->request->post();
			$id = $data['id'];
			$key = $data['key'];
			$model = $this->findModel($id);
//            return $id.$key;
			$qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET);
			$pictures = json_decode($model->pictures, true);
			unset($pictures[$key]);
			$newPictures = json_encode($pictures);
			$model->pictures = $newPictures;
			$qiniu->delete($key);
			$model->save();
			return $key;
		}
	}

}
